package com.watson.todolist;

import java.security.GeneralSecurityException;

import com.watson.todolist.constants.DatabaseConstants;
import com.watson.todolist.database.AccountManager;
import com.watson.todolist.database.DatabaseManager;
import com.watson.todolist.database.GenericEncryption;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This screen handles reseting the user password after a change password code
 * has been sent to their email
 * 
 * @author Donnie Ward
 * 
 */
public class ResetPassword extends Activity {

	/**
	 * This method is called when the activity is created.
	 * 
	 * @param savedInstanceState
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.reset_password);

		// Get buttons on screen
		Button updateAccount = (Button) findViewById(R.id.updateAccountButton);
		Button cancel = (Button) findViewById(R.id.registerCancel);

		cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), mainLoginPage.class);
				startActivity(intent);
			}
		});

		updateAccount.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Get text views on screen
				TextView codeBox = (TextView) findViewById(R.id.changePasswordCodeTextField);
				TextView password = (TextView) findViewById(R.id.enterPasswordTextField);
				TextView confirmPassword = (TextView) findViewById(R.id.confirmPasswordTextField);

				// Get intent extras
				String changePasswordCode = getIntent().getStringExtra("code")
						.trim();
				String userName = getIntent().getStringExtra("username");

				// Get text in input boxes
				String userInputCode = codeBox.getText().toString();
				String userInputPassword = password.getText().toString();
				String userInputConfirmPassword = confirmPassword.getText()
						.toString();

				if (!userInputCode.equals(changePasswordCode)) {
					Toast.makeText(v.getContext(),
							"Change password code is incorrect",
							Toast.LENGTH_SHORT).show();
				} else if (!userInputPassword.equals(userInputConfirmPassword)
						|| userInputConfirmPassword.equals("")) {
					Toast.makeText(v.getContext(),
							"Passwords must match and cannot be blank",
							Toast.LENGTH_SHORT).show();
				}

				// Handle correct change password code input and password input
				if (!userInputConfirmPassword.equals("")
						&& userInputCode.equals(changePasswordCode)
						&& userInputPassword.equals(userInputConfirmPassword)) {
					// Change user account password
					DatabaseManager dbManager = new DatabaseManager();
					SQLiteDatabase db = dbManager.open(getApplicationContext());
					AccountManager manager = new AccountManager(db);

					// Get account information
					Cursor c = manager.getUserAccountByUserName(userName);
					long userId = c.getLong(c
							.getColumnIndex(DatabaseConstants.ID));
					String emailAddress = c.getString(c
							.getColumnIndex(DatabaseConstants.ACCOUNT_TABLE_EMAIL_ADDRESS));
					String newPassword;

					// Update user account with new password
					try {
						newPassword = GenericEncryption.encrypt(password
								.getText().toString());
						manager.updateUserAccount(userId, userName,
								emailAddress, newPassword,
								DatabaseConstants.CHANGE_PASSWORD_REQUEST);

						// Close database
						dbManager.close();

						// Send user to login screen
						Intent intent = new Intent(v.getContext(),
								mainLoginPage.class);
						startActivity(intent);
					} catch (GeneralSecurityException e) {
						// Close database
						dbManager.close();

						Toast.makeText(v.getContext(),
								"Account failed to update", Toast.LENGTH_SHORT)
								.show();
						e.printStackTrace();
					}
				}
			}
		});

	}
}
